package co.fitstart.coach.web.controller;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.coach.entity.security.Login;
import co.fitstart.coach.service.BasicInformationService;
import co.fitstart.coach.service.CourseService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.service.RecordService;
import co.fitstart.coach.service.ResultReportService;
import co.fitstart.coach.service.ScheduleService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.course.ResultReport;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.course.schedule.ScheduleStatus;
import co.fitstart.entity.courseware.assessment.BasicData;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.user.StudentTargetData;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.entity.user.inbody.InbodyRecord;

/**
 * 成果报告
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("/rounds/{courseRoundId}/result-report")
public class ResultReportController {
    private static final Logger logger = LoggerFactory.getLogger(ResultReportController.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private ResultReportService resultReportService;
    
    @Autowired
    private BasicInformationService basicInformationService;
    
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RecordService recordService;
    
    /**
     * 成果报告展示页
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @WechatJsConfig
    public ModelAndView load(@Secure Login login,
                             @PathVariable("courseRoundId") Long courseRoundId,
                             @RequestParam(value="scheduleId", required=false) Long scheduleId,
                             @RequestParam(value="back", required=false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/result/result-report");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && courseRound.getFitnessGroup() != null) {
            Map<Integer, BwhRecord> bwhRecords = resultReportService.listBwhRecord(courseRound);
            
            BasicData basicData = basicInformationService.loadBasicData(courseRound);
            
            ResultReport resultReport = resultReportService.loadResultReport(courseRound);
            
            modelAndView.addObject("courseRound", courseRound);
            modelAndView.addObject("weeks", courseRound.getFitnessGroup().getWeeks());
            modelAndView.addObject("bwhRecords", bwhRecords);
            modelAndView.addObject("basicData", basicData);
            modelAndView.addObject("resultReport", resultReport);
            modelAndView.addObject("edit", courseRound.getCoach() == coach);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        if(courseRound.getCoach() != null && courseRound.getCoach().getId().equals(coach.getId())) {
            modelAndView.addObject("courseRound", courseRound);
            
         // 获取round所有已完成的schedule
            List<CourseSchedule> courseSchedules = scheduleService.list(courseRound, ScheduleStatus.FINISH);
            
            if(!courseSchedules.isEmpty()) {
                
                // 入营时间
                CourseSchedule firstSchedule = courseSchedules.get(courseSchedules.size() - 1);
                modelAndView.addObject("startTime", firstSchedule.getOccurDate());
                
                // Inbody 数据
                List<InbodyRecord> inbodyRecords = recordService.listInbodyRecoreds(courseRound);
                if(!inbodyRecords.isEmpty()) {
                    modelAndView.addObject("originalInbodyRecord", inbodyRecords.get(inbodyRecords.size()-1));
                    modelAndView.addObject("newInbodyRecord", inbodyRecords.get(0));
                }
            }
            
            // 三维数据
            List<BwhRecord> bwhRecords = recordService.listBwhRecords(courseRound);
            if(!bwhRecords.isEmpty()) {
                modelAndView.addObject("originalBwhRecord", bwhRecords.get(bwhRecords.size()-1));
                modelAndView.addObject("newBwhRecord", bwhRecords.get(0));
            }
            
            // 目标数据
            StudentTargetData studentTargetData = recordService.loadStudentTargetData(courseRound);
            if(studentTargetData != null) {
                modelAndView.addObject("studentTargetData", studentTargetData);
            }
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/edit-bwh", method = RequestMethod.GET)
    public ModelAndView editBwh(@Secure Login login,
                                @PathVariable("courseRoundId") Long courseRoundId,
                                @RequestParam("week") int week,
                                @RequestParam(value="scheduleId", required=false) Long scheduleId,
                                @RequestParam(value="back", required=false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/result/bwh-edit");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
            BwhRecord bwhRecord = resultReportService.loadBwhRecord(courseRound, week);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            modelAndView.addObject("week", week);
            modelAndView.addObject("bwhRecord", bwhRecord);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param bwhRecord
     * @return
     */
    @RequestMapping(value = "/edit-bwh", method = RequestMethod.PATCH)
    public @ResponseBody String onEditBwh(@Secure Login login,
                                          @PathVariable("courseRoundId") Long courseRoundId,
                                          BwhRecord bwhRecord) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
                resultReportService.editBwhRecord(courseRound, bwhRecord);
            }
            
            result.success().message("记录体重体脂三围成功");
        } catch (Exception e) {
            logger.error("ResultReportController#onEditBwh() error", e);
            result.fail().message("记录体重体脂三围失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/edit-change", method = RequestMethod.GET)
    public ModelAndView editChange(@Secure Login login,
                                   @PathVariable("courseRoundId") Long courseRoundId,
                                   @RequestParam(value="scheduleId", required=false) Long scheduleId,
                                   @RequestParam(value="back", required=false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/result/change-edit");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
            ResultReport resultReport = resultReportService.loadResultReport(courseRound);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            modelAndView.addObject("weeks", courseRound.getCourse().getWeeks());
            modelAndView.addObject("resultReport", resultReport);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param resultReport
     * @return
     */
    @RequestMapping(value = "/edit-change", method = RequestMethod.PATCH)
    public @ResponseBody String onEditChange(@Secure Login login,
                                             @PathVariable("courseRoundId") Long courseRoundId,
                                             ResultReport resultReport) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
                resultReportService.editChange(courseRound, resultReport);
            }
            
            result.success().message("编辑" + courseRound.getFitnessGroup().getWeeks() + "周改变成功");
        } catch (Exception e) {
            logger.error("ResultReportController#onEditChange() error", e);
            result.fail().message("编辑改变失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 总结编辑页
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/edit-summary", method = RequestMethod.GET)
    public ModelAndView editSummary(@Secure Login login,
                                    @PathVariable("courseRoundId") Long courseRoundId,
                                    @RequestParam(value="scheduleId", required=false) Long scheduleId,
                                    @RequestParam(value="back", required=false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/result/summary-edit");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
            ResultReport resultReport = resultReportService.loadResultReport(courseRound);
            
            if(resultReport != null) {
                modelAndView.addObject("courseRoundId", courseRoundId);
                modelAndView.addObject("summary", resultReport.getCoachSummary());
                modelAndView.addObject("wordsToStudent", resultReport.getWordsToStudent());
                modelAndView.addObject("scheduleId", scheduleId);
            }
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 编辑总结
     * @param login
     * @param courseRoundId
     * @param summary
     * @return
     */
    @RequestMapping(value = "/edit-summary", method = RequestMethod.PATCH)
    public @ResponseBody String onEditSummary(@Secure Login login,
                                              @PathVariable("courseRoundId") Long courseRoundId,
                                              @RequestParam(value="summary", required=false) String summary,
                                              @RequestParam(value="wordsToStudent", required=false) String wordsToStudent) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
                resultReportService.editSummary(courseRound, summary, wordsToStudent);
            }
            
            result.success().message("修改总结成功");
        } catch (Exception e) {
            logger.error("ResultReportController#onEditSummary() error", e);
            result.fail().message("修改总结失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param mediaId
     * @param suffix 后缀（before：入营时；after：结营时）
     * @return
     */
    @RequestMapping(value = "/upload-contrast-photo", method = RequestMethod.POST)
    public @ResponseBody String uploadContrastPhoto(@Secure Login login,
                                                    @PathVariable("courseRoundId") Long courseRoundId,
                                                    @RequestParam("mediaId") String mediaId,
                                                    @RequestParam("suffix") String suffix) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
                result = resultReportService.uploadContrastPhoto(courseRound, mediaId, suffix);
            } else {
                result.fail().message("图片上传失败");
            }
        } catch (BusinessException e) {
            result.fail().message(e.getMessage());
        } catch (Exception e) {
            logger.error("ResultReportController#uploadContrastPhoto() error", e);
            result.fail().message("图片上传失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
